﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.cms.presentation.Trees;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using umbraco.cms.businesslogic.media;
using umbraco;

namespace DigibizTree.Picker
{
    public class DigibizMediaTree : BaseMediaTree
    {

        public DigibizMediaTree(string app)
            : base(app)
        {
        }

        private const int NoAccessId = -123456789;

        private Media _userStartNodeMedia;
        private Media _definedStartNodeMedia;
        private Media _finalStartNodeMedia;
        private int? _determinedStartNodeId = null;

        /// <summary>
        /// Returns the Media object of the starting node for the current User. This ensures
        /// that the Media object is only instantiated once.
        /// </summary>
        protected Media UserStartNodeDoc
        {
            get
            {
                if (_userStartNodeMedia == null)
                {
                    _userStartNodeMedia = CurrentUser.StartMediaId <= 0 ? new Media(-1, true) : new Media(CurrentUser.StartMediaId);
                }
                return _userStartNodeMedia;
            }
        }

        /// <summary>
        /// Returns the Media object of the starting node that is defined in the prevalue editor. This ensures
        /// that the Media object is only instantiated once.
        /// </summary>
        protected Media DefinedStartNodeMedia
        {
            get
            {
                if (_definedStartNodeMedia == null)
                {
                    var definedId = this.GetStartNodeIdFromCookie(this.GetDataTypeId());

                    try
                    {
                        _definedStartNodeMedia = definedId <= 0 ? new Media(-1) : new Media(definedId);
                    }
                    catch (Exception ex)
                    {
                        _definedStartNodeMedia = new Media(-1);
                    }
                }
                return _definedStartNodeMedia;
            }
        }

        /// <summary>
        /// Determines the allowed start node id based on the users start node id and the 
        /// defined start node id in the data type.
        /// </summary>
        public override int StartNodeID
        {
            get
            {
                if (_determinedStartNodeId.HasValue)
                {
                    return _determinedStartNodeId.Value;
                }

                _determinedStartNodeId = this.GetStartNodeId(DefinedStartNodeMedia, UserStartNodeDoc);

                return _determinedStartNodeId.Value;
            }
        }

        /// <summary>
        /// Return the real start node that will be shown in the media tree.
        /// </summary>
        protected Media FinalStartNodeMedia
        {
            get
            {
                if (_finalStartNodeMedia == null)
                {
                    _finalStartNodeMedia = new Media(StartNodeID);
                }
                return _finalStartNodeMedia;
            }
        }

        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
            if (!this.SetNullTreeRootNode(StartNodeID, ref rootNode, app))
            {
                string rootText;
                string rootIcon;
                string rootNodeID;

                if (StartNodeID == -1)
                {
                    rootText = ui.GetText("media");
                    rootIcon = FolderIcon;
                    rootNodeID = StartNodeID.ToString();
                }
                else
                {
                    rootText = FinalStartNodeMedia.Text;
                    rootIcon = FinalStartNodeMedia.ContentTypeIcon;
                    rootNodeID = FinalStartNodeMedia.Id.ToString();
                }

                rootNode.Text = rootText;
                rootNode.Icon = rootIcon;
                rootNode.NodeID = rootNodeID;
                rootNode.Source = this.GetTreeServiceUrlWithParams(StartNodeID, this.GetDataTypeId());
                rootNode.Action = string.Format("javascript:openMedia({0});", rootNode.NodeID);
            }
        }

        protected override void OnBeforeNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e)
        {
            var xDoc = new XmlDocument();

            var xmlNode = umbraco.library.GetMedia(int.Parse(node.NodeID), false).Current.OuterXml;

            var xmlString = "<root>" + xmlNode + "</root>";
            var xml = XElement.Parse(xmlString);

            //Ensure that the NodeKey is passed through.
            node.Source = this.GetTreeServiceUrlWithParams(int.Parse(node.NodeID), this.GetDataTypeId());

            base.OnBeforeNodeRender(ref sender, ref node, e);
        }
    }
}
